package net.loyin.app.ctrl.admin;

import net.loyin.annotation.ControllerBind;
import net.loyin.annotation.CtrlMethod;
import net.loyin.app.model.SysMenu;
import net.loyin.app.model.SysRole;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户
 * Created by loyin on 16/1/12.
 */
@ControllerBind(route = "/admin/role")
public class SysRoleCtrl extends AdminBaseCtrl {

    public void index(){
        int pageNumber=this.getParaToInt("pageNumber",1);
        int pageSize=this.getParaToInt("pageSize",20);
        StringBuffer sql=new StringBuffer("select * from ");
        sql.append(SysRole.tableName);
        this.setAttr("page",SysRole.dao.paginate(pageNumber,pageSize,sql.toString()));
    }
    public void add(){
        String id=this.getPara(0);
        if(StringUtils.isNotBlank(id)){
            this.setAttr("po",SysRole.dao.findById(id));
            this.setAttr("roleMenuList",SysRole.dao.qryRoleMenuId(id));
        }
        this.setAttr("menuList", SysMenu.dao.find("select * from sys_menu where status=1 order by sort asc"));
    }
    /**返回角色json 数组*/
    @CtrlMethod(isAjax = true)
    public void roleJson(){
        List<SysRole> list=SysRole.dao.find("select id,name as text from sys_role where status=1 order by name");
        this.renderJson(list);
    }
    @CtrlMethod(isAjax = true)
    public void save(){
        SysRole entity=this.getModel(SysRole.class);
        if(entity!=null){
            String id=entity.getId();
            if(StringUtils.isEmpty(id)) {
                entity.save();
            }else{
                entity.update();
            }
            id=entity.getId();
            String[] menuList=this.getParaValues("menuList");
            SysRole.dao.cfgMenu(id,menuList);
            this.renderJsonMsg(JSON_RESULT_SUCCESS,"保存成功!");
        }else{
            this.renderJsonMsg(JSON_RESULT_ERROR,"保存失败!");
        }
    }
    @CtrlMethod(isAjax = true)
    public void del(){
        String id=this.getPara(0);
        try {
            if (StringUtils.isNotBlank(id)) {
                SysRole.dao.deleteById(id);
                this.renderJsonMsg(JSON_RESULT_SUCCESS,"删除成功!");
            } else {
                this.renderJsonMsg(JSON_RESULT_WARNNING, "缺少参数!");
            }
        }catch (Exception e){
            logger.error("删除异常",e);
            this.renderJsonMsg(JSON_RESULT_ERROR, "删除异常,可能存在引用,请先删除对应的数据!");
        }
    }
}
